package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.IDWorker;
import com.hmdp.utils.RedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    private final ISeckillVoucherService seckillVoucherService;
    private final IDWorker idWorker;



    public VoucherOrderServiceImpl(ISeckillVoucherService seckillVoucherService, IDWorker idWorker) {
        this.seckillVoucherService = seckillVoucherService;
        this.idWorker = idWorker;
    }

    // 加载 lua 脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    // 创建阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    // 设置线程任务
//    @PostConstruct  // 在初始化时就执行任务
//    private void init() {
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//    }
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    // 获取队列中的订单消息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    // 创建订单
//                    handlerVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("创建订单异常", e);
//                }
//            }
//        }
//    }

    // 创建单线程
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct  // 在初始化时就执行任务
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }


    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true) {
                try {
                    // 获取消息队列中的订单信息 XREADGROUP g1 c1 1 2000ms STREAMS key >
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 判断订单信息是否获取成功
                    if(read == null || read.isEmpty()) {
                        // 1. 获取失败，说明没有消息，继续下一次循环
                        continue;
                    }
                    // 解析消息
                    MapRecord<String, Object, Object> record = read.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 2. 获取成功，创建订单
                    handlerVoucherOrder(voucherOrder);
                    // ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("订单处理异常", e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true) {
                try {
                    // 获取 pending-list 中的订单信息 XREADGROUP g1 c1 1 2000ms STREAMS key 0
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    // 判断订单信息是否获取成功
                    if(read == null || read.isEmpty()) {
                        // 1. 获取失败，说明有异常
                        break;
                    }
                    // 解析消息
                    MapRecord<String, Object, Object> record = read.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 2. 获取成功，创建订单
                    handlerVoucherOrder(voucherOrder);
                    // ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("订单处理异常", e);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }

    private IVoucherOrderService proxy;

    /**
     * lua 脚本实现优惠券秒杀
     * @param voucherId
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1.执行 lua 脚本
        Long userId = UserHolder.getUser().getId();
        Long orderId = idWorker.nextId("order");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), orderId.toString()
        );
        // 2.判断结果是否为0
        assert result != null;
        int r = result.intValue();
        // 3.不为0，不能购买，返回异常
        if(r != 0) {
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 4.为0，可以购买，把优惠券id和用户id存入阻塞队列
//        Long orderId = idWorker.nextId("order");
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setVoucherId(voucherId);
//        voucherOrder.setUserId(userId);
        // 保存到阻塞队列
//        orderTasks.add(voucherOrder);
        // 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(orderId);
    }

    /**
     * 创建订单
     * @param voucherOrder
     */
    private void handlerVoucherOrder(VoucherOrder voucherOrder) {
        // 获取用户
        Long userId = voucherOrder.getUserId();
        // 设置分布式锁
        RedisLock redisLock = new RedisLock(stringRedisTemplate, "voucher" + userId);  // 自定义锁
        // 尝试获取锁
        boolean isLock = redisLock.tryLock(5);
        // 是否获取锁成功
        if(!isLock) {
            // 获取锁失败
            log.error("创建订单异常");
            return;
        }

        // 获取代理对象
        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            this.createVoucherOrder(voucherOrder);
        } finally {
            // 释放锁
            redisLock.unlock();
        }
    }

    /**
     * 优惠券秒杀
     * @param voucherId
     */
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        // 查询优惠券相关信息
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        // 判断优惠券是否在可购买范围内
//        if(LocalDateTime.now().isBefore(seckillVoucher.getBeginTime())) {
//            return Result.fail("不在可抢购时间内");
//        }
//        if(LocalDateTime.now().isAfter(seckillVoucher.getEndTime())) {
//            return Result.fail("已超出抢购时间");
//        }
//        // 如果可购买，判断优惠券数量是否足够
//        if(seckillVoucher.getStock() < 1) {
//            return Result.fail("优惠券已被抢空");
//        }
//
//        // 确保一人一单
//        Long userId = UserHolder.getUser().getId();
//        // 设置分布式锁
//        RedisLock redisLock = new RedisLock(stringRedisTemplate, "voucher" + userId);  // 自定义锁
////        RLock redisLock = redissonClient.getLock("voucher" + userId);
//        // 尝试获取锁
//        boolean isLock = redisLock.tryLock(5);
//        // 是否获取锁成功
//        if(!isLock) {
//            // 获取锁失败，返回错误
//            return Result.fail("同一个用户只能下一单");
//        }
//
//        // 获取代理对象
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            // 释放锁
//            redisLock.unlock();
//        }
//
//
//    }


    /**
     * 解决超卖问题
     *
     * @param voucherOrder
     * @return
     */
    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        // 确保一人一单(子线程不能从主线程直接获取 id)
        Long userId = voucherOrder.getUserId();
        int count = this.query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherOrder.getVoucherId()).count();
        if(count > 0) {
            log.error("重复下单");
            return;
        }
        // 扣减库存(乐观锁解决超卖问题)
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")  // set stock = stock - 1
                .eq("voucher_id", voucherOrder.getVoucherId())  // where id = ?
                .gt("stock", 0)  // stock > 0
                .update();
        if(!success) {
            log.error("优惠券已被抢空");
            return;
        }
        // 创建订单

        save(voucherOrder);
    }
}
